<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员名称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="税后金额" prop="atMin">
        <el-input
          v-model="queryParams.atMin"
          placeholder="请输入税后金额最小值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>—
       <el-form-item label="" prop="atMax">
        <el-input
          v-model="queryParams.atMax"
          placeholder="请输入税后金额最大值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="类别" prop="personId">
        <el-select v-model="queryParams.personId" placeholder="会员类别" clearable>
          <el-option v-for="dict in dict.type.person_id" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="类别" prop="payState">
        <el-select v-model="queryParams.payState" placeholder="纳税状态" clearable>
          <el-option v-for="dict in dict.type.notice" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['member:member:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['member:member:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['member:member:export']"
        >导出</el-button>
      </el-col>
      <el-button
        type="info"
        icon="el-icon-upload2"
        size="mini"
        @click="handleImport"
      >导入</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <!-- 用户导入对话框 -->
<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
  <el-upload
	ref="upload"
	:limit="1"
	accept=".xlsx, .xls"
	:headers="upload.headers"
	:action="upload.url + '?updateSupport=' + upload.updateSupport"
	:disabled="upload.isUploading"
	:on-progress="handleFileUploadProgress"
	:on-success="handleFileSuccess"
	:auto-upload="false"
	drag
  >
	<i class="el-icon-upload"></i>
	<div class="el-upload__text">
	  将文件拖到此处，或
	  <em>点击上传</em>
	</div>
	<div class="el-upload__tip" slot="tip">
	  <el-checkbox v-model="upload.updateSupport" />
	  <el-link type="info" style="font-size:12px" @click="importTemplate"></el-link>
	</div>
	<div class="el-upload__tip" style="color:red" slot="tip"></div>
  </el-upload>
  <div slot="footer" class="dialog-footer">
	<el-button type="primary" @click="submitFileForm">确 定</el-button>
	<el-button @click="upload.open = false">取 消</el-button>
  </div>
</el-dialog>


    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员名称" align="center" prop="memberName" />
      <el-table-column label="会员图片" align="center" prop="memberImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.memberImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="税号" align="center" prop="dutyParagraph" />

      <el-table-column label="类别" align="center" prop="personId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.person_id" :value="scope.row.personId"/>
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="用户手机号" align="center" >
        <template slot-scope="scope">
  	      {{scope.row.phone?scope.row.phone.replace(/(\d{3})(\d{4})(\d{4})/,"$1****$3"):""}}
        </template>
      </el-table-column>

      <el-table-column label="省" align="center" prop="addressProvince" />
      <el-table-column label="市" align="center" prop="addressCity" />
      <el-table-column label="区" align="center" prop="addressDistrict" />
      <el-table-column label="详细地址" align="center" prop="addressParticulars" />

      <el-table-column label="收入(元)" align="center" prop="income" sortable/>
      <el-table-column label="纳税金额(元)" align="center" prop="payTaxes" sortable/>
      <el-table-column label="税后金额(元)" align="center" prop="at" sortable/>
       <el-table-column label="邮箱" :show-overflow-tooltip="true" align="center" prop="emailAddress"/>
       <el-table-column label="是否已缴纳税务" align="center" prop="payState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.notice" :value="scope.row.payState"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-comment"
            @click="handlerecord(scope.row)"
            v-hasPermi="['member:member:edit']"
          >易告知消息</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['member:member:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['member:member:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗纳税记录页面 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <p>易告知消息：{{form.content}}</p>

        </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="guanbijilu()">确 定</el-button>
    </div>
</el-dialog>

    <!-- 添加或修改会员信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员名称" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入会员名称" />
        </el-form-item>
        <el-form-item label="会员图片" prop="memberImg">
          <image-upload v-model="form.memberImg"/>
        </el-form-item>
        <el-form-item label="税号" prop="dutyParagraph">
          <el-input v-model="form.dutyParagraph" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="类别" prop="personId">
              <el-select v-model="form.personId" placeholder="会员类别">
                <el-option
                  v-for="dict in dict.type.person_id"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="联系号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系号码" />
        </el-form-item>

        <el-form-item label=省份 prop="addressProvince">
        <el-select
        v-model="form.addressProvince"
        placeholder="请选择省"
        @change="changePro">
        <el-option
          v-for="item in addressData"
          :key="item.code"
          :label="item.name"
          :value="item.name">
        </el-option>
      </el-select>
      </el-form-item>

       <el-form-item label=市 prop="addressCity">
      <el-select
        v-model="form.addressCity"
        placeholder="请选择市"
        @change="changeCity">
        <el-option
          v-for="item in cityData"
          :key="item.code"
          :label="item.name"
          :value="item.name">
        </el-option>
      </el-select>
       </el-form-item>

    <el-form-item label=区 prop="addressDistrict">
      <el-select
        v-model="form.addressDistrict"
        placeholder="请选择区"
        @change="changeArea">
        <el-option
          v-for="item in areaData"
          :key="item.code"
          :label="item.name"
          :value="item.name">
        </el-option>
      </el-select>
    </el-form-item>

      <el-form-item label="" prop="addressParticulars">
          <el-input v-model="form.addressParticulars" placeholder="请输入详细地址" />
        </el-form-item>



        <el-form-item label="收入" prop="income">
          <el-input-number v-model="form.income"
          :precision="2"
          :controls="false"
           placeholder="请输入收入" />
        </el-form-item>

      <el-form-item label="邮箱" prop="emailAddress">
          <el-input v-model="form.emailAddress" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="纳税状态" prop="personId">
              <el-select v-model="form.payState" placeholder="纳税状态">
                <el-option
                  v-for="dict in dict.type.notice"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember
} from "@/api/member/member";

import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode
} from "element-china-area-data";

//全国省市区街道数据
import address from "@/utils/address.json"

/**导入功能 */
import { getToken } from "@/utils/auth";
// 导入模板接口importTemplate
import { importTemplate } from "@/api/system/user";


import { errorMonitor } from "events";

export default {
  name: "Member",
  dicts: ["person_id", "delete_or_not", "notice"],
  data() {
    return {
      //地区三级联动
      //  省数据
      addressData: [],
      //  市数据
      cityData: [],
      // 区数据
      areaData: [],

      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/member/member/importData"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员信息表格数据
      memberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberName: null,
        memberImg: null,
        dutyParagraph: null,
        personId: null,
        phone: null,
        income: null,
        payTaxes: null,
        at: null,
        state: null,
        atMin: null,
        atMax: null,
        payState: null
      },
      //纳税记录弹窗是否显示
      dialogFormVisible:false,
      //纳税记录
      jilu:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        memberName: [
          { required: true, message: "请输入会员名称", trigger: "blur" },
          { min: 2, message: "长度最少2个字符", trigger: "blur" },
          {
            validator: function(rule, value, callback) {
              if (/^[\u4e00-\u9fa5]+$/.test(value) == false) {
                callback(new Error("请输入中文"));
              } else {
                //校验通过
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        dutyParagraph: [
          { required: true, message: "请输入税号", trigger: "blur" },
          {
            min: 15,
            max: 20,
            message: "税号最少为15位，最大为20位",
            trigger: "blur"
          }
        ],
        personId: [
          { required: true, message: "请选择纳税类型", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: "change"
          }
        ],
        addressProvince: [
          { required: true, message: "请选择省", trigger: "change" },
        ],
        addressCity:[
           { required: true, message: "请选择市", trigger: "change" },
        ],
        addressDistrict:[
           { required: true, message: "请选择区", trigger: "change" },
        ],
        addressParticulars: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],

        income: [
          { required: true, message: "收入不能为空", trigger: "blur" }
          // {oninput:value=value.replace(/[^\d.]/g,''),message:"收入只能输入数字"}
        ],
        emailAddress:[
          { required: true, message: '邮箱不可为空', trigger: 'blur' },
          {
            validator: function (rule, value, callback) {
              if (/^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value) == false) {
                callback(new Error('请输入正确格式的邮箱'))
              } else {
                //校验通过0000000000.
                callback()
              }
            },
            trigger: 'blur'
          }
        ],

      }
    };
  },
  created() {
    // 省份数据初始化
    this.addressData = address;
    //获取会员集合
    this.getList();
  },
  methods: {
    /** 获取地址三级联动 */
    changePro(e) {
      // 从省中过滤出市的数据
      this.cityData = this.addressData.filter((item) => {
        return item.name == e;
      })[0].children;
      // 省发生改变的时候 清空输入框市区街道的内容
      this.form.district = "";
      this.form.city = "";
      // 省发生更改时 该表空区街道数据的内容
      this.areaData = [];
    },
    // 市更改
    changeCity(e) {
      // 获取到区的数据
      this.areaData = this.cityData.filter(
        (item) => item.name == e
      )[0].children;
      // 清空数据后面对应数组的数据
      this.form.district = "";
    },
    // 区更改
    changeArea(e) {
      let temp = this.areaData.filter((item) => item.name == e);
      // 获取到区的code码
      this.form.regionalNumber = temp[0].code;
      // 获取到街道的数据
      this.jdData = this.areaData.filter((item) => item.name == e)[0].children;
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询会员信息列表 */
    getList() {
      this.loading = true;
      listMember(this.queryParams).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.cityData=[];
      // 区数据
      this.areaData=[];
    },
    // 表单重置
    reset() {
      this.form = {
        memberId: null,
        memberName: null,
        memberImg: null,
        dutyParagraph: null,
        personId: null,
        phone: null,
        income: null,
        payTaxes: null,
        at: null,
        state: 0,
        payState: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.memberId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(this.dict);

      if (row.state == 1) {
        this.$modal.msgError("您已删除无法修改");
      } else {
        this.reset();
        const memberId = row.memberId || this.ids;
        getMember(memberId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改会员信息";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      //交稅的邏輯
      if (this.form.income <= 5000 && this.form.personId == 1) {
        this.form.payTaxes = 0;
        this.form.at = this.form.income;
      } else if (this.form.income > 5000 && this.form.personId == 1) {
        this.form.payTaxes = this.form.income * 0.03;
        this.form.at = this.form.income - this.form.payTaxes;
      } else if (this.form.income <= 5000 && this.form.personId == 3) {
        this.form.payTaxes = 0;
        this.form.at = this.form.income;
      } else if (this.form.income > 5000 && this.form.personId == 3) {
        this.form.payTaxes = this.form.income * 0.03;
        this.form.at = this.form.income - this.form.payTaxes;
      } else if (this.form.income <= 1000000 && this.form.personId == 2) {
        this.form.payTaxes = this.form.income * 0.05;
        this.form.at = this.form.income - this.form.payTaxes;
      } else if (
        this.form.income > 1000000 &&
        this.form.income <= 3000000 &&
        this.form.personId == 2
      ) {
        this.form.payTaxes = this.form.income * 0.1;
        this.form.at = this.form.income - this.form.payTaxes;
      } else if (this.form.income > 3000000 && this.form.personId == 2) {
        this.form.payTaxes = this.form.income * 0.25;
        this.form.at = this.form.income - this.form.payTaxes;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.memberId != null) {
            updateMember(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMember(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.payState == 1) {
        this.$modal.msgWarning("该用户未交税！！！不可删除");
      } else {
        const memberIds = row.memberId || this.ids;
        this.$modal
          .confirm('是否确认删除会员信息编号为"' + memberIds + '"的数据项？')
          .then(function() {
            return delMember(memberIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "member/member/export",
        {
          ...this.queryParams
        },
        `member_${new Date().getTime()}.xlsx`
      );
    },
    handlerecord(row){
         this.reset();
        const memberId = row.memberId || this.ids;
        getMember(memberId).then(response => {
          this.form = response.data;
          this.dialogFormVisible = true;
          this.title = "易告知记录";
        });
    },
     guanbijilu(){
    this.dialogFormVisible=false;
  }
  }
};
</script>

